<template>
  <!-- 搜索区和新增按钮 -->
  <el-row :gutter="20" class="mt-4">
    <el-col :span="8">
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索角色名称" 
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" icon="Search" @click="handleSearch" />
        </template>
      </el-input>
    </el-col>
    <el-col :span="2">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </el-col>
  </el-row>

  <!-- 角色表格 -->
  <el-table 
    :data="roleList" 
    border 
    stripe 
    style="width: 100%; margin-top: 20px"
    v-loading="loading"
  >
    <el-table-column prop="roleName" label="角色名称" width="150" />
    <el-table-column prop="description" label="描述" />
    <!-- 状态列 -->
    <el-table-column label="状态" width="150" align="center">
      <template #default="scope">
        <div v-if="scope.row.isActive === true" class="status-button enabled">
          启用
        </div>
        <div v-else class="status-button disabled">
          禁用
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="createdAt"  label="创建时间"  width="180">
      <template #default="{ row }">
        {{ formatTime(row.createdAt) }}
      </template>
    </el-table-column>
    <el-table-column  prop="updatedAt"  label="更新时间"  width="180">
      <template #default="{ row }">
        {{ formatTime(row.updatedAt) }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="250" align="center">
      <template #default="scope">
        <el-button 
          size="small" 
          type="primary" 
          @click="handleEdit(scope.row)"
        >
          编辑
        </el-button>
        <el-button 
          size="small" 
          type="danger" 
          @click="handleDelete(scope.row)"
          :disabled="scope.row.isSuperAdmin"
        >
          删除
        </el-button>
        <el-button 
          size="small" 
          type="success" 
          @click="handleAssignPerm(scope.row)"
        >
          分配权限
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <Pagination
      v-model:pageIndex="pagination.pageIndex"
      v-model:pageSize="pagination.pageSize"
      :total="pagination.total"
      @page-change="loadData"
      class="pagination"
  />

  <!-- 角色表单弹窗 -->
  <RoleForm 
    v-model="showFormDialog"
    :role="formRole"
    @save="handleFormSave"
    @updateVisible="handleFormClose"
  />

  <!-- 权限分配弹窗 -->
  <RoleMenuPermission
    v-model="showMenuPermissionDialog "
    :role-id="currentRoleId"
    :role-name="currentRoleName"
    :initial-permissions="currentPermissions"
    @success="fetchRoles"
    @updateVisible="menuPermissionFormClose"
  />
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import RoleForm from '@/components/business/RoleForm.vue'
import Pagination from '@/components/common/Pagination.vue'
import RoleMenuPermission from '../../components/business/RoleMenuPermission.vue'
import { roleApi } from '@/api/role.js'; // 引入角色管理 API

// 角色列表数据
const roleList = ref([])
const loading = ref(false) // 加载状态

// 搜索和分页状态
const searchKeyword = ref('')
const pagination = reactive({
  pageIndex: 1,   //当前页码
  pageSize: 5,    //页码显示数
  total: 0          //共有多少条数据
});

// 加载数据
const loadData = (pageIndex, pageSize) => {
  if (pageIndex) pagination.pageIndex = pageIndex
  if (pageSize) pagination.pageSize = pageSize
  loadRoles()
};

// 新增/编辑表单弹窗状态
const showFormDialog = ref(false)
const formRole = ref(null)

// 权限分配相关状态
const showMenuPermissionDialog  = ref(false)
const currentRoleId = ref('')
const currentRoleName = ref('')
const currentPermissions = ref([])

// 加载角色列表
const loadRoles = async (params = {}) => {
  try {
    loading.value = true
    // 传递分页和搜索参数给后端
     const requestParams = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      searchKeyword: searchKeyword.value
    };
    const response = await roleApi.getRoles(requestParams);    
    roleList.value = response.data || []
    // 共有多少条数据
    pagination.total = response.totalCount || 0
  } catch (error) {
    ElMessage.error('加载角色列表失败：' + (error.message || '网络错误'))
    roleList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
};

// 页面初始化加载数据
onMounted(() => {
  loadRoles()
})

// 搜索角色
const handleSearch = () => {
  pagination.pageIndex = 1; // 重置页码为第一页
  loadRoles()
};

// 重新加载角色列表
const fetchRoles = () => {
  loadRoles()
}

// 新增角色
const handleAdd = () => {
  formRole.value = { 
    roleNname: '', 
    description: '',
    isActive: true // 默认启用状态
  }
  showFormDialog.value = true
}

// 编辑角色
const handleEdit = (row) => {
  formRole.value = JSON.parse(JSON.stringify(row)); // 深拷贝，避免修改原数据
  showFormDialog.value = true
}

// 删除角色
const handleDelete = async (row) => {  
  if (row.roleName == '超级管理员') {
    ElMessage.warning('超级管理员角色不能删除')
    return
  }
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.roleName}"吗？删除后将无法恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    loading.value = true
    await roleApi.deleteRole(row.id)
    ElMessage.success('角色删除成功')
    loadRoles() // 重新加载列表
  } catch (error) {
    if (error === 'cancel') return; // 用户取消操作
    // 处理后端返回的错误信息
    const errorMsg = error.response?.data?.message || '删除角色失败'
    ElMessage.error(errorMsg)
  } finally {
    loading.value = false
  }
}

// 分配权限
const handleAssignPerm = async (role) => {
  try {
    loading.value = true
    // 获取相关信息
    const res = await roleApi.getRoleMenuPermissions(role.id);
    // 传递信息
    currentPermissions.value = res.data || []
    currentRoleId.value = String(role.id)
    currentRoleName.value = role.roleName
    showMenuPermissionDialog.value = true
  } catch (error) {
    ElMessage.error('获取角色权限失败：' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 保存表单（新增/编辑）
const handleFormSave = async (roleData) => {
  try {
    loading.value = true
    if (roleData.id) {
      // 编辑操作
      let res =await roleApi.updateRole(roleData.id, roleData)
      console.log(res);
      if(res.message == '角色已禁用'){
        await roleApi.enableRole(roleData.id)
      }
      ElMessage.success('角色编辑成功')
    } else {
      // 新增操作
       // 确保不传递id字段（新增时应由后端生成）
      const roleDataForCreate = {
        roleName: roleData.roleName,
        description: roleData.description,
        IsActive: roleData.IsActive
      }
      await roleApi.createRole(roleDataForCreate)
      ElMessage.success('角色创建成功')
    }   
    showFormDialog.value = false
    loadRoles() // 重新加载列表
  } catch (error) {
    const errorMsg = error.response?.data?.message || '操作失败'
    ElMessage.error(errorMsg)
  } finally {
    loading.value = false
  }
}

// 关闭新增/编辑弹窗
const handleFormClose = (visible) => {
  showFormDialog.value = visible
  if (!visible) {
    formRole.value = null; // 关闭时清空表单数据
  }
}

// 关闭权限弹窗
const menuPermissionFormClose  = (visible) => {
  showMenuPermissionDialog.value = visible
}


const formatTime = (time) => {
  if (!time) return '--'
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}
</script>

<style scoped>
.pagination{
  justify-content: center;
  margin-top: 20px;
}

/* 表格操作列按钮间距 */
:deep(.el-table__column:last-child .el-button) {
  margin-right: 5px;
}

/* 状态按钮样式 */
.status-button {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 5px;
  font-weight: bold;
  text-align: center;
  cursor: pointer;
}

.enabled {
  background-color: #d0f5a579;
  color: #469f2e;
  border: 1px solid #d0f5a5;
}

.disabled {
  background-color: #ffe6e68c;
  color: #e44444;
  border: 1px solid #f9d2d2;
}

/* 加载状态覆盖整个表格 */
:deep(.el-table__body-wrapper) {
  min-height: 200px;
}
</style>